package offer;

/**
 * 剑指 Offer 42. 连续子数组的最大和
 */
public class MaxSubArray {
    public static void main(String[] args) {

        int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4, 16};
        nums = new int[]{8, -19, 5, -4, 20};
        System.out.println(maxSubArray(nums));
    }

    public static int maxSubArray(int[] nums) {
        int max = nums[0];
        int tmp = 0;
        for (int i = 0; i < nums.length; i++) {
            tmp += nums[i];
            if (tmp <= nums[i]) {
                if (max <= nums[i]) {
                    max = nums[i];
                    tmp = max;
                } else {
                    tmp = nums[i];
                }
            } else {
                max = Math.max(max, tmp);
            }
        }
        return max;
    }

    public static int maxSubArray1(int[] nums) {
        int max = nums[0];
        int temp = nums[0];
        for (int i = 1; i < nums.length; i++) {
            temp = +nums[i];
            temp = Math.max(temp, max);
            max = Math.max(temp, nums[i]);
            temp = max;
        }
        return max;
    }
}
